<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
    >

      <el-table-column label="ID" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="简称">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="值">
        <template slot-scope="{row}">
          <span>{{ row.value }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述">
        <template slot-scope="{row}">
          <span>{{ row.desc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <!-- <el-button type="success" size="mini" @click="handleUpdateRoleMenu(row,$index)">
            菜单
          </el-button> -->
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!--      编辑-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="简称" prop="name">
          <el-input v-model="temp.name" clearable />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="temp.value" clearable />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="temp.desc"
            type="textarea"
            :rows="4"
          />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormroleMenuListVisible">
      <el-form ref="dataMenuForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item>
          <el-tree
            ref="tree"
            :data="roleMenuList"
            :default-checked-keys="roleMenuDefaultList"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormroleMenuListVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateRoleMenu()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import { roleList, roleCreate, roleUpdate, roleDelete, menuList, roleMenuList, roleMenuUpdate } from '@/api/rbac'
// import { menuList, roleMenuList, roleMenuUpdate } from '@/api/rbac'
import { systemConfigList, systemConfigCreate, systemConfigDelete } from '@/api/system'
import waves from '@/directive/waves' // waves directive
import { formatJson, notifySuccess, my_confirm, getFileUrl } from '@/utils/tool'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'RoleMenuList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
        // name: undefined
      },
      temp: {
        id: '',
        name: '',
        value: '',
        desc: ''
        // parent_id: '',
        // name: '',
        // type: '',
        // url: '',
        // sort: ''
      },
      centerTypeOptions: [],
      dialogFormVisible: false,
      dialogFormroleMenuListVisible: false,
      roleMenuList: [], // 所有的菜单
      roleMenuDefaultList: [], // 默认选中的菜单
      roleMenuListId: '',
      defaultProps: {
        children: 'menuTwo',
        label: 'name'
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        menu: '菜单'
      },
      rules: {
        name: [{ required: true, message: '简称必填', trigger: 'change' }],
        value: [{ required: true, message: '值必填', trigger: 'change' }],
        desc: [{ required: true, message: '描述必填', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      systemConfigList(this.listQuery).then(response => {
        this.list = response.data
        this.centerTypeOptions = response.data.typeList
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        name: ''
      }
    },
    // 添加
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          systemConfigCreate(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      console.log(row)
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'update'
      // this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          const tempData = Object.assign({}, this.temp)
          systemConfigCreate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
          })
        }
      })
    },
    // 删除
    handleDelete(row, index) {
      my_confirm(this, () => {
        systemConfigDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    // 获取树形菜单列表的所有数据
    // handleUpdateRoleMenu(row) {
    //   this.dialogStatus = 'menu'
    //   this.dialogFormroleMenuListVisible = true
    //   this.roleMenuListId = row.id
    //   menuList().then(response => {
    //     this.roleMenuList = response.data
    //   })
    //   // 获取默认选中的菜单
    //   roleMenuList({ roleId: row.id }).then(response => {
    //     this.roleMenuDefaultList = response.data
    //   })
    // },
    // updateRoleMenu() {
    //   var selectdMenu = this.$refs.tree.getCheckedNodes(false, true)
    //   var menuArr = []
    //   selectdMenu.forEach(function(item) {
    //     menuArr.push(item.id)
    //     if (Number(item.parent_id) !== 0) {
    //       menuArr.push(item.parent_id)
    //     }
    //   })
    //   var menuStr = menuArr.toString()
    //   roleMenuUpdate({ roleId: this.roleMenuListId, menuStr: menuStr }).then(() => {
    //     this.dialogFormroleMenuListVisible = false
    //     notifySuccess(this, '修改成功')
    //   })
    // },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '名称']
        const filterVal = ['id', 'name']
        const data = formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户角色表'
        })
        this.downloadLoading = false
      })
    },
    returnImageUrl(url) {
      return getFileUrl(url)
    }
  }
}
</script>
